package com.atguigu.tingshu.payment.service.impl;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private RabbitService rabbitService;

    @Override
    public void savePaymentInfo(String paymentType, String orderNo, Long userId, BigDecimal totalAmount) {
        //  本质保存数据;
        PaymentInfo paymentInfo = new PaymentInfo();
        //  赋值：
        paymentInfo.setUserId(userId);
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        paymentInfo.setAmount(totalAmount);
        paymentInfo.setPaymentStatus(SystemConstant.ORDER_STATUS_UNPAID);
        paymentInfo.setContent(paymentType.equals(SystemConstant.PAYMENT_TYPE_ORDER)? "订单支付" : "充值");
        //  保存
        this.save(paymentInfo);
    }

    @Override
    public void updatePaymentStatus(Transaction result) {
        //  修改payment_info;
        String orderNo = result.getOutTradeNo();
        //  通过orderNo 查询交易记录对象
        PaymentInfo paymentInfo = this.getOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderNo));
        //  判断
        if (null == paymentInfo || !paymentInfo.getPaymentStatus().equals(SystemConstant.ORDER_STATUS_UNPAID)){
            //  一种是已支付，一种是取消;
            return;
        }
        paymentInfo.setPaymentStatus(SystemConstant.ORDER_STATUS_PAID);
        paymentInfo.setOutTradeNo(result.getTransactionId());
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(result.toString());
        //  修改表数据：
        this.updateById(paymentInfo);
        //  修改订单或充值的状态;
        String routingKey = paymentInfo.getPaymentType().equals(SystemConstant.PAYMENT_TYPE_ORDER)? MqConst.ROUTING_ORDER_PAY_SUCCESS : MqConst.ROUTING_RECHARGE_PAY_SUCCESS;
        //  发送消息;
        rabbitService.sendMessage(MqConst.EXCHANGE_ORDER,routingKey,orderNo);
    }
}
